package com.onpositive.knowledge.model.values;

import java.util.List;

import com.onpositive.knowledge.model.IThing;
import com.onpositive.knowledge.model.IUniverse;
import com.onpositive.knowledge.model.impl.BasicUniverseProperty;
import com.onpositive.semantic.model.api.meta.DefaultMetaKeys;
import com.onpositive.semantic.model.api.meta.IHasMeta;
import com.onpositive.semantic.model.api.property.IProperty;
import com.onpositive.semantic.model.api.realm.IRealm;
import com.onpositive.semantic.model.api.realm.Realm;
import com.onpositive.semantic.model.api.realm.RealmProviderAdapter;

public class MPProvider extends RealmProviderAdapter<Object> {

	@Override
	public IRealm<Object> getRealm(IHasMeta meta, Object parent) {
		if (parent instanceof PropertyValuePair) {
			
			BasicUniverseProperty pm = (BasicUniverseProperty) ((PropertyValuePair) parent).property;
			IUniverse universe = pm.getUniverse();
			return toCalc(pm, universe);
		}
		String stringValue = DefaultMetaKeys.getStringValue(meta, DefaultMetaKeys.ID_KEY);
		IUniverse value = DefaultMetaKeys.getService(meta, IUniverse.class);
		IProperty property = value.getProperty(parent, stringValue);
		return toCalc((BasicUniverseProperty) property,value);
	}

	protected IRealm<Object> toCalc(BasicUniverseProperty pm, IUniverse universe) {
		Realm<Object> o = new Realm<Object>();
		IRealm<IThing> all = universe.all();
		for (IThing a : all) {
			Object value = pm.getValue(a);
			DescribedValue ds = (DescribedValue) value;
			if (ds != null) {
				Object value2 = ds.value;
				if (value2 instanceof List) {
					List l = (List) value2;
					for (Object oo : l) {
						o.add(oo);
					}
				} else {
					o.add(value2);
				}
			}
		}
		return o;
	}

}
